// SPDX-License-Identifier: GPL-2.0
/*
 * CXL.MEM WITH DEVDAX
 *
 * (C) 2024.07.07 BuddyZhang1 <buddy.zhang@aliyun.com>
 */
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#include <sys/mman.h>

#define DEVPATH		"/dev/dax0.0"
#define MAP_SIZE	(16 * 1024 * 1024) /* 16MiB */
#define MAP_VADDR	(0x6000000000)
#define errExit(msg)	do { perror(msg); exit(EXIT_FAILURE); } while (0)

int main()
{
	void *mem;
	int fd;

	/* OPEN DEVDAX */
	fd = open(DEVPATH, O_RDWR);
	if (fd < 0)
		errExit("OPEN DEVDAX FAILED.\n");
	
	/* ALLOC VIRTUIAL MAPPING DEVDAX */
	mem = mmap((void *)MAP_VADDR, MAP_SIZE,
		   PROT_READ | PROT_WRITE,
		   MAP_SHARED,
		   fd,
		   0);
	if (mem == MAP_FAILED)
		errExit("MMAP DEVDAX FAILED.\n");

	/* ACCESS CXL.MEM */
	*(char *)mem = 'D';
	printf("READ FROM DEVDAX: %c\n", *(char *)mem);

	/* RECLAIM */
	munmap(mem, MAP_SIZE);
	close(fd);

	return 0;
}
